package drift

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log/slog"
	"net/http"
)

func SendSlackMessage(slackUrl string, message string) error {
	type SlackMessage struct {
		Text string `json:"text"`
	}

	httpClient := &http.Client{}
	slackMessage := SlackMessage{
		Text: message,
	}
	jsonData, err := json.Marshal(slackMessage)
	if err != nil {
		slog.Error("failed to marshal slack message", "error", err)
		return err
	}

	request, err := http.NewRequest("POST", slackUrl, bytes.NewBuffer(jsonData))
	if err != nil {
		slog.Error("failed to create slack drift request", "error", err)
		return err
	}

	request.Header.Set("Content-Type", "application/json")
	resp, err := httpClient.Do(request)
	if err != nil {
		slog.Error("failed to send slack drift request", "error", err)
		return err
	}
	if resp.StatusCode != 200 {
		body, err := io.ReadAll(resp.Body)
		if err != nil {
			slog.Error("failed to read response body", "error", err)
			return err
		}
		slog.Error("failed to send slack drift request", "status code", resp.Status, "body", body)
		msg := fmt.Sprintf("failed to send slack drift request. %v. Message: %v", resp.Status, body)
		return fmt.Errorf("%s", msg)
	}
	resp.Body.Close()
	return nil
}
